<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>最佳拍档</title>
    <meta name="keywords" content="最佳拍档">
    <meta name="description" content="最佳拍档">
    <script th:src="@{/UEditor/ueditor.config.js}" src="/UEditor/ueditor.config.js"></script>
    <script th:src="@{/UEditor/ueditor.all.js}" src="/UEditor/ueditor.all.js"></script>
    <style>
        .right h2{
            margin: 10px 0;
        }
        .right li{
            margin-bottom: 10px;
        }
        .layui-form-label{
            width: 130px;
        }
        .layui-input-block {
            margin-left: 160px;
        }

        #container iframe{
            padding-left: 0px;
            padding-top: 0px;
            width: 800px;
        }
    </style>
</head>
<body>
<div class="right p20" style="margin-left: 200px;">
    <input type="hidden" id="userRole" th:value="${userRole}">
    <fieldset class="layui-elem-field layui-field-title">
        <legend>商品品牌信息</legend>
    </fieldset>
    <form class="layui-form" lay-filter="CommodityForm" id="commodity_form">
        <div class="layui-form-item">
            <label class="layui-form-label">公司名</label>
            <div class="layui-input-block">
                <input type="text" name="company" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">1688店铺名称</label>
            <div class="layui-input-block">
                <input type="text" name="shopName" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">淘宝分销</label>
            <div class="layui-input-inline">
                <input type="radio" name="taobaoDistribution" value="1" title="可以" checked disabled>
                <input type="radio" name="taobaoDistribution" value="0" title="不可以" disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">社群分销</label>
            <div class="layui-input-inline">
                <input type="radio" name="communityDistribution" value="1" title="可以" checked disabled>
                <input type="radio" name="communityDistribution" value="0" title="不可以" disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">其他分销渠道</label>
            <div class="layui-input-block">
                <input type="text" name="otherDistribution" placeholder="请填写其他分销渠道" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 10px;">
            <legend>商品详情</legend>
        </fieldset>
        <div class="layui-form-item">
            <label class="layui-form-label">商品状态</label>
            <div class="layui-input-block">
                <input type="text" name="commodityStatus" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">编号</label>
            <div class="layui-input-block">
                <input type="text" name="commodityNum" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">商品名称</label>
            <div class="layui-input-block">
                <input type="text" name="commodityName" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">商品链接</label>
            <div class="layui-input-block">
                <input type="text" name="commodityLink" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">规格</label>
            <div class="layui-input-block">
                <input type="text" name="specification" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">供货价（元）</label>
            <div class="layui-input-block">
                <input type="text" name="supplyPrice" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">控价</label>
            <div class="layui-input-block">
                <input type="text" name="floorPrice" autocomplete="off" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">一件代发</label>
            <div class="layui-input-inline">
                <input type="radio" name="dropShipping" value="1" title="是" checked disabled>
                <input type="radio" name="dropShipping" value="0" title="否" disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">运费</label>
            <div class="layui-input-block">
                <input type="text" name="fare" autocomplete="off" class="layui-input" disabled>
            </div>
            <div style="padding-left: 160px;padding-top: 10px;" hidden="hidden">
                <input id="fareSelector" type="file">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <textarea name="remark" id="remark" placeholder="请填写备注" class="layui-textarea" disabled></textarea>
            </div>
        </div>
        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 10px;">
            <legend>商品运营策略</legend>
        </fieldset>
        <div class="layui-form-item">
            <label class="layui-form-label">淘宝定价</label>
            <div class="layui-input-block">
                <input type="text" name="taobaoPrice" autocomplete="off" placeholder="未定价" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">渠道供货价</label>
            <div class="layui-input-block">
                <input type="text" name="channelPrice" autocomplete="off" placeholder="暂无" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">计划上架时间</label>
            <div class="layui-input-block">
                <input type="text" class="layui-input" name="planTime" placeholder="请选择计划上架时间" id="startDateid" readonly disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">实际上架时间</label>
            <div class="layui-input-block">
                <input type="text" class="layui-input" name="shelfTime" placeholder="请选择实际上架时间" id="dueDateid" readonly disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">淘宝链接</label>
            <div class="layui-input-block">
                <input type="text" name="taobaoLink" autocomplete="off" placeholder="暂无" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">退货地址</label>
            <div class="layui-input-block">
                <input type="text" name="returnAddress" autocomplete="off" placeholder="暂无" class="layui-input" disabled>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">商品详情</label>
            <div class="layui-input-block" style="width: 800px;">
                <textarea id="container" name="commodityDetail" disabled></textarea>
            </div>
        </div>
        <div class="layui-form-item" style="padding-top: 10px;">
            <div class="layui-input-block">
                <button class="layui-btn" id="SubmitBtn" lay-submit lay-filter="submitCommodityForm">立即提交</button>
            </div>
        </div>
    </form>
</div>

</body>
<script src="https://unpkg.com/cos-js-sdk-v5/dist/cos-js-sdk-v5.min.js"></script>
<script type="text/javascript">
    let cos = new COS({
        SecretId: 'AKIDfATcXDdpmW3LOCl48xWptjKflcDZgYAY',
        SecretKey: 'B6mDOK1TggSzGI4buynMgkY8SXMvFK9j',
    });
    let Bucket = 'dev-1308272144'
    let Region = 'ap-guangzhou'
    let folderName = "cms"
    let customerId = "";
    let files = [];
    let attachments = [];
    let ue;
    let OriginalCommodityData = {}
    let commodityId = "";

    window.onload = function(){
        commodityId = GetQueryString("commodityId")
        if(isNotNull(commodityId)){
            initFormData(commodityId);
            if(document.getElementById('container')!=null){
                ue = UE.getEditor('container');
            }
            ue.ready(function() {
                ue.setHeight(400);
            })
            //固定导航栏
            $('a[href="/Admin/Commodity/CommodityManagement"]').parent().addClass('layui-this');
            $('a[href="/Admin/Commodity/CommodityManagement"]').parent().parent().parent().addClass('layui-nav-itemed');
        }else{
            history.go(-1);
        }
    }

    //根据用户角控制组件是否能操作
    function operate_permission(){
        let userRole = $("#userRole").val();
        if(userRole.indexOf("priceClerk") != -1 && OriginalCommodityData.signingStatus == 2 && OriginalCommodityData.commodityStatus == "未定价"){//商品定价员填写淘宝定价、渠道供货价
            $('input[name="taobaoPrice"]').removeAttr('disabled');
            $('input[name="channelPrice"]').removeAttr('disabled');
            ue.setDisabled();
        }else if(userRole.indexOf("taobaoManage") != -1 && OriginalCommodityData.commodityStatus == '已上架淘宝'){//淘宝运营上架后还能修改商品详情
            $('input[name="commodityDetail"]').removeAttr('disabled');
            ue.setEnabled();
        }else if(userRole.indexOf("taobaoManage") != -1 && OriginalCommodityData.commodityStatus == '已安排上架'){//淘宝运营上架商品
            $('input[name="shelfTime"]').removeAttr('disabled');
            $('input[name="returnAddress"]').removeAttr('disabled');
            $('input[name="taobaoLink"]').removeAttr('disabled');
            $('input[name="commodityDetail"]').removeAttr('disabled');
            ue.setEnabled();
        }else if(userRole.indexOf("deptManage") != -1){
            $("#commodity_form *").removeAttr('disabled');
            $('input[name="commodityStatus"]').attr("disabled","disabled");
            $('input[name="commodityNum"]').attr("disabled","disabled");
            ue.setEnabled();
        }else{
            ue.setDisabled();
            $("#SubmitBtn").hide();
        }
    }

    //初始化数据
    function initFormData(commodityId){
        initCommodityInfo(commodityId);
    }

    //初始化商品信息
    function initCommodityInfo(commodityId) {
        $.ajax({
            url: '/commodity/'+commodityId,
            type: 'get',
            data: {},
            dataType: 'json', // 用于设置响应体的类型 注意 跟 data 参数没关系！！！
            success: function (res) {
                OriginalCommodityData = res.data;
                //根据用户角控制组件是否能操作
                operate_permission();
                layui.use('form', function(){
                    let form = layui.form;
                    //给表单赋值
                    form.val("CommodityForm", {
                        "company": res.data.company,
                        "shopName": res.data.shopName,
                        "taobaoDistribution": res.data.taobaoDistribution,
                        "communityDistribution": res.data.communityDistribution,
                        "otherDistribution": res.data.otherDistribution,
                        "commodityStatus": res.data.commodityStatus,
                        "commodityNum": res.data.commodityNum,
                        "commodityName": res.data.commodityName,
                        "commodityMap": res.data.commodityMap,
                        "commodityLink": res.data.commodityLink,
                        "specification": res.data.specification,
                        "supplyPrice": res.data.supplyPrice,
                        "floorPrice": res.data.floorPrice,
                        "dropShipping": res.data.dropShipping,
                        "fare": res.data.fare,
                        "remark": res.data.remark,
                        "taobaoPrice": res.data.taobaoPrice,
                        "channelPrice": res.data.channelPrice,
                        "planTime": res.data.planTime,
                        "shelfTime": res.data.shelfTime,
                        "taobaoLink": res.data.taobaoLink,
                        "returnAddress": res.data.returnAddress
                    });
                    ue.setContent(res.data.commodityDetail);
                });
            }
        });
    }

    //表单提交
    layui.use(['form','layer'], function(){
        let form = layui.form;
        let layer = layui.layer;
        form.on('submit(submitCommodityForm)',function (res) {
            let Original_Data ={}
            $.ajax({
                url: '/commodity/'+commodityId,
                type: 'get',
                data: {},
                dataType: 'json', // 用于设置响应体的类型 注意 跟 data 参数没关系！！！
                success: function (res) {
                    if(res.data){
                        Original_Data = res.data;
                        let msg = "";
                        let userRole = $("#userRole").val();
                        if(userRole.indexOf("priceClerk") != -1 && Original_Data.signingStatus == 2 && Original_Data.commodityStatus == "未定价"){//商品定价员填写淘宝定价、渠道供货价
                            let taobaoPrice = $('input[name="taobaoPrice"]').val();
                            let channelPrice = $('input[name="channelPrice"]').val();
                            if(isNotNull(taobaoPrice) && isNotNull(channelPrice)){
                                Original_Data.taobaoPrice = taobaoPrice;
                                Original_Data.channelPrice = channelPrice;
                                Original_Data.commodityStatus = "未上架淘宝";
                                msg = "商品定价成功！";
                            }else{
                                layer.msg("请填写完整淘宝定价和渠道供货价！");
                                return false;
                            }
                        }else if(userRole.indexOf("taobaoManage") != -1 && Original_Data.commodityStatus == '已上架淘宝'){//淘宝运营可以修改已上架商品的详情
                            let commodityDetail = ue.getContent();
                            Original_Data.commodityDetail = commodityDetail;
                            msg = "修改商品详情成功！";
                        }else if(userRole.indexOf("taobaoManage") != -1 && Original_Data.commodityStatus == '已安排上架'){//淘宝运营上架商品
                            let shelfTime = $('input[name="shelfTime"]').val();
                            let returnAddress = $('input[name="returnAddress"]').val();
                            let taobaoLink = $('input[name="taobaoLink"]').val();
                            let commodityDetail = ue.getContent();
                            if(isNotNull(shelfTime) && isNotNull(returnAddress) && isNotNull(taobaoLink) && isNotNull(commodityDetail)){
                                Original_Data.shelfTime = shelfTime;
                                Original_Data.returnAddress = returnAddress;
                                Original_Data.taobaoLink = taobaoLink;
                                Original_Data.commodityDetail = commodityDetail;
                                Original_Data.commodityStatus = "已上架淘宝";
                                msg = "上架商品成功！";
                            }else{
                                layer.msg("请填写完整上架商品信息再提交噢！");
                                return false;
                            }
                        }else if(userRole.indexOf("deptManage") != -1){
                            Original_Data.company = $('input[name="company"]').val();
                            Original_Data.shopName = $('input[name="shopName"]').val();
                            Original_Data.taobaoDistribution = $('input[name="taobaoDistribution"]:checked').val();
                            Original_Data.communityDistribution = $('input[name="communityDistribution"]:checked').val()
                            Original_Data.otherDistribution = $('input[name="otherDistribution"]').val();
                            Original_Data.commodityName = $('input[name="commodityName"]').val();
                            Original_Data.commodityMap = $('input[name="commodityMap"]').val();
                            Original_Data.commodityLink = $('input[name="commodityLink"]').val();
                            Original_Data.specification = $('input[name="specification"]').val();
                            Original_Data.supplyPrice = $('input[name="supplyPrice"]').val();
                            Original_Data.floorPrice = $('input[name="floorPrice"]').val();
                            Original_Data.dropShipping = $('input[name="dropShipping"]').val();
                            Original_Data.fare = $('input[name="fare"]').val();
                            Original_Data.remark = $("#remark").val();
                            Original_Data.taobaoPrice = $('input[name="taobaoPrice"]').val();
                            Original_Data.channelPrice = $('input[name="channelPrice"]').val();
                            Original_Data.shelfTime = $('input[name="shelfTime"]').val();
                            Original_Data.taobaoLink = $('input[name="taobaoLink"]').val();
                            Original_Data.returnAddress = $('input[name="returnAddress"]').val();
                            Original_Data.commodityDetail = ue.getContent();
                            msg = "修改商品成功！";
                            if(Original_Data.signingStatus == 2 && Original_Data.commodityStatus == "未上架淘宝"){
                                let planTime = $('input[name="planTime"]').val();
                                if(isNotNull(planTime)){
                                    Original_Data.planTime = planTime;
                                    Original_Data.commodityStatus = "已安排上架";
                                    msg = "商品已安排上架！";
                                }
                            }
                        }
                        if(isNotNull(msg)){
                            $.ajax({
                                type:"PUT",
                                url:'/commodity/detail/edit',
                                data:JSON.stringify(Original_Data),
                                dataType:'json',
                                contentType: 'application/json; charset=UTF-8',
                                success:function(req){
                                    layer.msg(msg);
                                    // 两秒后重载表格数据
                                    setTimeout(function(){
                                        window.location.href = "http://" + window.location.host + "/Admin/Commodity/CommodityManagement";
                                    }, 2000);
                                    return false;
                                },
                                error:function(e){
                                    layer.msg("出错啦！")
                                }
                            })
                        }
                    }else{
                        layer.mag("出错啦！");
                    }
                }
            });
            return false;
        })
    });

    //搜索
    function search(){
        layui.use(['table', 'layer'], function () {//layui 模块引用，根据需要自行修改
            let layer = layui.layer, table = layui.table;
            table.reload('tableid', {
                where: {
                    searchStr:$("#keyword").val()
                }
                ,page: {
                    pageNum: 1 //重新从第 1 页开始
                }
            });
        })
    }

    //回车搜索
    function keydownSearch() {
        let event = window.event || arguments.callee.caller.arguments[0];
        if (event.keyCode == 13)
        {
            search();
        }
    }

    //渲染日期控件
    layui.use('laydate', function(){
        let laydate = layui.laydate;
        laydate.render({
            elem: '#startDateid',
            trigger: 'click'
        });
    });

    layui.use('laydate', function(){
        let laydate = layui.laydate;
        laydate.render({
            elem: '#dueDateid',
            trigger: 'click'
        });
    });

    //文件上传
    layui.use('upload', function(){
        let upload = layui.upload;
        //执行实例
        let uploadInst = upload.render({
            elem: '#UploadData' //绑定元素
            ,url: '' //上传接口
            ,accept: 'images' //允许上传的文件类型
            ,auto: false //选择文件后不自动上传
            ,choose: function(obj){
                //将每次选择的文件追加到文件队列
                // files = obj.pushFile();
                //预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
                obj.preview(function(index, file, result){
                    // console.log(index); //得到文件索引
                    // console.log(file); //得到文件对象
                    // console.log(result); //得到文件base64编码，比如图片
                    let File = {fileInfo:file,data:result}
                    files.push(File)
                    //obj.resetFile(index, file, '123.jpg'); //重命名文件名，layui 2.3.0 开始新增

                    //这里还可以做一些 append 文件列表 DOM 的操作
                    let arr_index = files.length-1
                    $("#file_content").append("<p style='color: #1ea0fa;padding-bottom: 3px;' id='file_list"+arr_index+"'><span style='padding-right: 5px;font-size: 16px;'>"+file.name+"</span><span style='padding-top: 2px;font-weight: 600;vertical-align: middle;'><i class='layui-icon' onclick='del_file("+arr_index+")'>&#x1006;</i></span></p>")
                    //obj.upload(index, file); //对上传失败的单个文件重新上传，一般在某个事件中使用
                    //delete files[index]; //删除列表中对应的文件，一般在某个事件中使用
                });
            }
        });
    });

    //删除需要上传的文件
    function del_file(index){
        files.splice(index, 1);
        $("#file_list"+index).remove();
    }

    //获取地址栏参数
    function GetQueryString(name){
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if(r!=null)return  unescape(r[2]);
        return null;
    }

    /**
     * 判断值是否不为空
     * @param {Object} val
     */
    function isNotNull(val){
        if(val!=='undefined' && val!=="" && val!=null){
            return true
        }
        return false
    }

    //添加商品图片上传
    $("#imgSelector").change(function () {
        $("#original_img").remove();
        files = $("#imgSelector")[0].files;
    });

    //授权申请附件上传
    $("#fileSelector").change(function () {
        let file = $("#fileSelector")[0].files;
        let url = uploadCOS(file);
        if(isNotNull(url)){
            attachments.push(url);//上传完毕添加到attachments中
            randerAttachList(1);//重新渲染附件列表
        }
    });

    //渲染附件列表：0为展示列表，1为可删除列表
    function randerAttachList(flag){
        $("#attachment_content").html("");//先清空附件列表显示
        for(let i in attachments){
            let attach = attachments[i];
            let filename = attach.substring(attach.lastIndexOf("/")+1);
            if(flag == 0){
                $("#attachment_content").append("<p style='color: #1ea0fa;padding-bottom: 3px;' id='attachment_list"+i+"'><a href='"+attach+"' target='_blank'>"+filename+"</a></p>")
            }else if(flag == 1){
                $("#attachment_content").append("<p style='color: #1ea0fa;padding-bottom: 3px;' id='attachment_list"+i+"'><a href='"+attach+"' target='_blank'>"+filename+"</a><span style='padding-top: 2px;font-weight: 600;vertical-align: middle;color: red;padding-left: 3px;'><i class='layui-icon' onclick='del_attchment("+i+")'>&#x1006;</i></span></p>")
            }
        }
    }

    //删除文件
    function del_attchment(index){
        attachments.splice(index, 1);
        $("#attachment_list"+index).remove();
    }

    // 将表单数据序列化为一个json对象，例如 {"name":"zs", "age":10}
    // 使用：var jsonObj = $("#formId").serializeObject();
    $.fn.serializeObject = function()
    {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    //上传文件到存储桶
    function uploadCOS(file_arr) {
        let backUrls = "";
        //上传图片到存储桶
        for (let i in file_arr){
            let fileName = file_arr[i].name
            cos.putObject({
                Bucket: Bucket, /* 必须 */
                Region: Region,     /* 存储桶所在地域，必须字段 */
                Key:  folderName + "/" + fileName,/*文件夹+文件名称 必须 */
                Body: file_arr[i], // 上传文件对象
                onProgress: function(progressData) {
                    console.log(JSON.stringify(progressData));
                    let backUrl = "https://" + Bucket + ".cos."+ Region + ".myqcloud.com/" + folderName + "/" + fileName;
                    if(backUrls == ""){
                        backUrls = backUrl;
                    }else{
                        backUrls += "," + backUrl;
                    }
                    return backUrls;
                }
            }, function(err, data) {
                console.log(err || data);
                // if(data){
                //     let backUrl = "https://" + Bucket + ".cos."+ Region + ".myqcloud.com/" + folderName + "/" + fileName;
                //     if(backUrls == ""){
                //         backUrls = backUrl;
                //     }else{
                //         backUrls += "," + backUrl;
                //     }
                // }
            });
        }
        return backUrls;
    }

    function test(){
        var html = ue.getContent();
        console.log("正文部分："+html)
    }

</script>

</html>